package bestTeam.WalkieDoggie.client.Composites;

import java.util.ArrayList;
import java.util.Date;

import bestTeam.WalkieDoggie.client.Location;
import bestTeam.WalkieDoggie.client.WalkieDoggie;
import bestTeam.WalkieDoggie.client.walkieStatus;
import bestTeam.WalkieDoggie.client.Serializables.UserProfileData;
import bestTeam.WalkieDoggie.client.Serializables.UserRequest;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.maps.client.InfoWindowContent;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.maps.client.geocode.DirectionQueryOptions;
import com.google.gwt.maps.client.geocode.Directions;
import com.google.gwt.maps.client.geocode.Waypoint;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.maps.client.overlay.MarkerOptions;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;


public class RequestOfFriend extends Composite {

	private Anchor userLabel;
	private Button confirmButton;
	private MapWidget map;

	private boolean isVolunteered=false;

	private userProfileComp userComp;


	@SuppressWarnings("deprecation")
	public RequestOfFriend(final UserRequest request,final boolean isAddressPrivate){

		for (int i =0;i<request.getVolunteers().length;i++){

			if (request.getVolunteers()[i].equals(WalkieDoggie.loginInfo.getUserData().getId()))
				isVolunteered = true;
		}

		VerticalPanel verticalPanel = new VerticalPanel();

		HorizontalPanel horizontalPanel = new HorizontalPanel();

		confirmButton = new Button();
		userLabel = new Anchor(request.getUserName());

		userLabel.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				userComp = new userProfileComp(WalkieDoggie.requestsOwnersMap.get(request),isAddressPrivate);
				userComp.setPopupPosition(WalkieDoggie.header_comp.getAbsoluteLeft()+300, WalkieDoggie.header_comp.getAbsoluteTop()+200);
				userComp.setGlassEnabled(true);
				userComp.show();
			}
		});

		if(isVolunteered){
			confirmButton.setText("UnVolunteer");			
		}
		else{
			confirmButton.setText("Volunteer");		

		}
		confirmButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				if(WalkieDoggie.loginInfo.isNewUser()){
					WalkieDoggie.mainPanel.clear();
					WalkieDoggie.mainPanel.add(WalkieDoggie.profile_comp);
				}
				else if(!isVolunteered){
					isVolunteered=true;
					confirmRequest(request);
					confirmButton.setText("UnVolunteer");

				}
				else{
					isVolunteered=false;
					confirmButton.setText("Volunteer");
					UNconfirmRequest(request);
				}
			}

		});




		horizontalPanel.add(confirmButton);

		loadMap(request,horizontalPanel);

		verticalPanel.add(userLabel);
		verticalPanel.add(horizontalPanel);

		initWidget(verticalPanel);
	}



	public void checkResizeOfMap(){
		
		if(map!=null)
			map.checkResize();
	}


	public void UNconfirmRequest(UserRequest request) {
		String[] volunteers = removeCurrentUserAsVolunteer(request.getVolunteers());
		request.setVolunteers(volunteers);
		if ((request.getApprovedWalkerID()!=null) && (request.getApprovedWalkerID().equals(WalkieDoggie.loginInfo.getUserData().getId()))){
			request.setApprovedWalkerID(null);
			request.setStatus(walkieStatus.NEW);
			WalkieDoggie.usersService.setCredits(WalkieDoggie.loginInfo.getUserData().getId(),-2, new AsyncCallback<Void>() {

				@Override
				public void onSuccess(Void result) 
				{					

					WalkieDoggie.loginInfo.getUserData().setCredit(WalkieDoggie.loginInfo.getUserData().getCredit()-2);
					WalkieDoggie.updateCounters();					
				}

				@Override
				public void onFailure(Throwable caught) 
				{
					WalkieDoggie.handleError(caught);
				}
			});
			
		}
		WalkieDoggie.requestService.UpdateRequest(request, new AsyncCallback<Void>() {
			@Override
			public void onSuccess(Void result) {

				WalkieDoggie.home_comp.displayWalkiesList();

			}

			@Override
			public void onFailure(Throwable caught) {
				WalkieDoggie.handleError(caught);
			}
		});

	}


	private String[] removeCurrentUserAsVolunteer(String[] volunteers) {
		ArrayList<String> newVolunteers = new ArrayList<String>();
		String currnetUserId = WalkieDoggie.loginInfo.getUserData().getId();

		for (String volunteer : volunteers) {

			if(!volunteer.equals(currnetUserId))
				newVolunteers.add(volunteer);
		}

		return (String[])newVolunteers.toArray(new String[0]);
	}

	public void confirmRequest(UserRequest request) {
		String[] volunteers = addCurrnetUserAsVolunteer(request.getVolunteers());
		request.setVolunteers(volunteers);
		WalkieDoggie.requestService.UpdateRequest(request, new AsyncCallback<Void>() {
			@Override
			public void onSuccess(Void result) {

				WalkieDoggie.home_comp.displayWalkiesList();

			}

			@Override
			public void onFailure(Throwable caught) {
				WalkieDoggie.handleError(caught);
			}
		});

	}



	private String[] addCurrnetUserAsVolunteer(String[] volunteers) {
		String[] newVolunteers = new String[volunteers.length+1];
		for (int i=0 ; i<volunteers.length ; i++){
			newVolunteers[i] = volunteers[i];
		}

		newVolunteers[volunteers.length] = WalkieDoggie.loginInfo.getUserData().getId();

		return newVolunteers;
	}

	private String intToTimeFrame(int timeFrame) {
		switch (timeFrame) {
		case 1: return "Morning";
		case 2: return "Noon";
		case 3: return "evening";

		default:
			break;
		}
		return "dont care";


	}

	private void loadMap(final UserRequest request,final HorizontalPanel horizontalPanel) {
		/*
		 * Asynchronously loads the Maps API.
		 *
		 * The first parameter should be a valid Maps API Key to deploy this
		 * application on a public server, but a blank key will work for an
		 * application served from localhost.
		 */
		Maps.loadMapsApi("AIzaSyA6APFS4_eVtj7UXM_oplwHLRtUOtPmvVE", "2", false, new Runnable() {
			public void run() {
				buildMap(request,horizontalPanel);
			}
		});

	}

	private void buildMap(UserRequest request, final HorizontalPanel horizontalPanel) {
		// Open a map centered on request owner adress
		String userName = request.getUserName();

		UserProfileData user = WalkieDoggie.requestsOwnersMap.get(request);

		Location l = user.getGeoLocation();

		LatLng loc = null;
		boolean isValidAdress = false;

		if(l==null){// not supposed to happen
			loc = LatLng.newInstance(32.1141185, 34.7960162);
		} else {
			loc = LatLng.newInstance(l.getLat(), l.getLng());
			isValidAdress = true;
		}

		//String str =  "location";

		map = new MapWidget(loc, 17);
		String strw = "" + (Window.getClientWidth()/2) +"px";
		map.setSize(strw, "200px");

		// Add some controls for the zoom level
		map.addControl(new LargeMapControl());

		if (isValidAdress){
			// Add a marker
			MarkerOptions mo2 = MarkerOptions.newInstance();
			//String infoStr = ""+request.getUserName()+": "+request.getDate()+" - "+request.getTimeFrame();
			map.addOverlay(new Marker(loc));

			// Add an info window to highlight a point of interest

			//	    map.getInfoWindow().open(map.getCenter(),
			//	        new InfoWindowContent(str));
		}

		SimplePanel sp = new SimplePanel();
		String width = "" + (Window.getClientWidth()/8) +"px";
		sp.setSize(width, "100px");



		if(!(WalkieDoggie.loginInfo.getUserData().getGeoLocation()==null)){
			// generate a polyline from the logedin user location to the requestOwner location

			Location userLoc = WalkieDoggie.loginInfo.getUserData().getGeoLocation();
			LatLng  userLocLatlng = LatLng.newInstance(userLoc.getLat(), userLoc.getLng());


			Waypoint wp1 = new Waypoint(userLocLatlng);
			Waypoint wp2 = new Waypoint(loc);
			Waypoint[] waypoints = new Waypoint[2];
			waypoints[0] = wp1;
			waypoints[1] = wp2;
			DirectionQueryOptions options = new DirectionQueryOptions(map);
			options.setRetrievePolyline(true);

			Directions.loadFromWaypoints(waypoints, options);

			// adds a marker on the map
			MarkerOptions mo1 = MarkerOptions.newInstance();
			String infoStr = "your house";
			//String infoStr = ""+request.getUserName()+": "+request.getDate()+" - "+request.getTimeFrame();
			mo1.setTitle(infoStr);

			map.addOverlay(new Marker(userLocLatlng,mo1));

		}

		horizontalPanel.add(sp);

		horizontalPanel.add(map);

	}



}
